import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSpace,
  type FormInstance,
  type FormRules
} from 'element-plus'
import { defineComponent, reactive, toRefs } from 'vue'

import { type IUserPageItem, userApi } from '@/apis'

import { formData, type IFormData } from './ResetPasswordDialog.define'

export default defineComponent({
  name: 'ResetPasswordDialog',
  emits: ['success'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      formRef: {} as FormInstance,
      formModel: formData(),
      formRules: {
        password: [{ required: true, message: '密码不能为空' }]
      } as FormRules<IFormData>,
      submitLoading: false,
      selectedRecord: {} as IUserPageItem
    })

    /**
     * 打开
     * @description 供父组件调用
     */
    function open(data: IUserPageItem, password: string) {
      state.selectedRecord = data
      state.formModel.password = password
      state.show = true
    }

    function handleClose() {
      state.show = false
      state.submitLoading = false
      state.selectedRecord = Object.create(null)
      state.formModel = formData()
      state.formRef.clearValidate()
    }

    function handleSubmit() {
      state.formRef.validate(async valid => {
        if (valid) {
          try {
            state.submitLoading = true

            await userApi.resetPassword(
              state.selectedRecord.id,
              state.formModel
            )

            handleClose()
            emit('success')
          } catch (error) {
            state.submitLoading = false
          }
        }
      })
    }

    return {
      ...toRefs(state),
      open,
      handleSubmit,
      handleClose
    }
  },
  render() {
    return (
      <ElDialog
        v-model={this.show}
        title="重置密码"
        width="600px"
        beforeClose={this.handleClose}
        destroyOnClose
      >
        {{
          default: () => (
            <ElForm
              ref={(e: any) => (this.formRef = e)}
              model={this.formModel}
              rules={this.formRules}
            >
              <ElFormItem prop="password">
                <ElInput
                  v-model={this.formModel.password}
                  type="password"
                  placeholder="请输入新密码"
                  showPassword
                />
              </ElFormItem>
            </ElForm>
          ),
          footer: () => (
            <ElSpace>
              <ElButton onClick={this.handleClose}>取消</ElButton>
              <ElButton
                type="primary"
                loading={this.submitLoading}
                onClick={this.handleSubmit}
              >
                确定
              </ElButton>
            </ElSpace>
          )
        }}
      </ElDialog>
    )
  }
})
